<template>
  <div class="container">
    <a-modal v-model:visible="visible" title="台词配音" @cancel="handleCancel" width="500px" centered>
      <!-- 开始时间 -->
      <div class="startTime flex mTop">
        <span class="startTime-left label">开始时间</span>
        <a-input-number style="width: 100px" :rules="customRules" addon-after="秒" :step="0.1" :min="0"
          v-model:value="start_time" />
      </div>
      <!-- 音色选择 -->
      <div class="tone-select flex mTop">
        <div class="tone-select-left label mRg-10px">音色选择</div>
        <div class="tone-select-right flex border">
          <!-- 音色头像 -->
          <div class="tone-avatar">
            <img :src="audioConfig.img" alt="" />
            <strong class="tone-name">{{ audioConfig.name }}</strong>
          </div>
          <!-- 操作按钮 -->
          <div class="operate flex">
            <!-- 替换选择 -->
            <a-spin :spinning="false">
              <span class="swap-icon" @click="scriptAudioSelectionShowModal()"><swap-outlined style="font-size: 14px" />
                替换</span>
            </a-spin>

            <!-- 音频播放器 -->
            <audio @ended="handleAudioEnded" ref="audioRef" :src="audioConfig.audio_url" style="display: none"></audio>

            <a-spin :spinning="isSpining">
              <!-- 暂停按钮 -->
              <span class="play-icon" v-if="isPlaying" @click="pauseAudioHandle()">
                <pause-outlined />
                暂停
              </span>
              <!-- 播放按钮 -->
              <span class="play-icon" v-else @click="playAudioHandle()">
                <caret-right-outlined />试听
              </span>
            </a-spin>
          </div>
        </div>
      </div>
      <!-- 配音音量 -->
      <div class="dubbing-volume mTop flex">
        <div class="dubbing-volume-left label mRg-20px">配音音量</div>
        <div class="dubbing-volume-right">
          <span class="min-volume">1</span>
          <a-slider :min="1" :max="11" class="volume-slider" v-model:value="volume" @change="changeVolume" />
          <span class="max-volume"> 11</span>
        </div>
      </div>
      <!-- 底部操作样式 -->
      <template #footer>
        <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
    <ScriptAudioSelection ref="scriptAudioSelection" @closeAudioSelection="closeAudioSelection"></ScriptAudioSelection>
  </div>
</template>
<script>
import {
  defineComponent,
  reactive,
  toRefs,
  onMounted,
  nextTick,
  ref,
  watch,
} from "vue";
import {
  SwapOutlined,
  ClockCircleOutlined,
  CaretRightOutlined,
  PauseOutlined,
} from "@ant-design/icons-vue";
// 音色选中组件
import ScriptAudioSelection from "./ScriptAudioSelection.vue";
import request from "@/common/utils/request";
import _ from "lodash";
export default defineComponent({
  components: {
    SwapOutlined,
    ClockCircleOutlined,
    CaretRightOutlined,
    PauseOutlined,
    ScriptAudioSelection,
  },
  setup(props, context) {
    const state = reactive({
      visible: false, //控制页面弹窗打开
      audioConfig: {}, //全局音乐配置
      isPlaying: false, //播放状态
      isSpining: false, //spin加载
      isValueChange: false,
      start_time: 0,
      volume: 0,
    });
    // 弹窗开启
    const showModal = (info) => {
      console.log(info);
      // 初始化数据
      state.audioConfig = reactive(JSON.parse(JSON.stringify(info)));
      console.log(state.audioConfig);
      state.start_time = state.audioConfig.start_time / 1000; //初始化的时间需要处于1000
      state.volume = state.audioConfig.volume + 1; //初始化需要+1
      state.visible = true;
      isAudioConfigChange.value = true;
    };

    // 音色选择弹窗组件
    const scriptAudioSelection = ref(null);
    // 打开音色选择弹窗
    const scriptAudioSelectionShowModal = () => {
      pauseAudioHandle();
      scriptAudioSelection.value.showModal({
        ...state.audioConfig,
        volume: state.volume,
      });
    };
    // 判断配置项是否改变
    let isAudioConfigChange = ref(true);
    // 音色弹窗选中成功回调，接收传值
    const closeAudioSelection = (info) => {
      isAudioConfigChange.value = _.isEqual(info, {
        ...state.audioConfig,
        volume: state.volume,
      });
      state.audioConfig = {
        ...state.audioConfig,
        ...info,
      };
      state.volume = info.volume;
      console.log(isAudioConfigChange.value, "弹窗关闭数据是否改变");
    };
    const audioRef = ref(null); //音频播放实例

    // 音频播放完成
    const handleAudioEnded = () => {
      audioRef.value.currentTime = 0; //音频重置到开始播放时间
      state.isPlaying = false; //播放按钮设置成暂停
    };
    // 暂停播放音频
    const pauseAudioHandle = () => {
      state.isPlaying = false;
      audioRef.value && audioRef.value.pause();
    };
    // 监听音频是否改变
    const changeVolume = (val) => {
      console.log(state.audioConfig.volume, val - 1);
      pauseAudioHandle();
      isAudioConfigChange.value =
        state.audioConfig.volume == val - 1 ? true : false;
    };
    // 点击取消
    const handleCancel = () => {
      state.isShowModal = false;
      audioRef.value.currentTime = 0;
      pauseAudioHandle();
    };
    // 弹窗关闭
    const handleOk = (e) => {
      let paramsObj = {
        ...state.audioConfig,
        volume: state.volume - 1, //展示为+1操作，提交给后端是-1操作
        start_time: state.start_time * 1000, //提交时候需要将秒转换成毫秒
        isChange: isAudioConfigChange.value,
      };
      // 将修改的值传给父组件
      context.emit("closeglobalDubbing", paramsObj);
      // 关闭弹窗
      state.visible = false;
    };
    // 音频播放
    const playAudioHandle = () => {
      // 关闭正在播放的音频
      pauseAudioHandle();
      // 判断数据无变化
      if (isAudioConfigChange.value) {
        state.isPlaying = !state.isPlaying;
        nextTick(() => {
          audioRef.value && audioRef.value.play();
        });
        return;
      } else {
        // 数据变化
        state.isSpining = true; //开启加载
        request
          .get("/work_ai", "/user/shotstack/textToVoice", {
            ...state.audioConfig,
            timbre_id: state.audioConfig.voice_type,
            text: "智能配音是一种利用人工智能技术实现的语音合成功能，它可以将文本内容转换成逼真的人类语音",
          })
          .then((res) => {
            let tiem = setInterval(() => {
              request
                .get("/work_ai", "/user/shotstack/getVoice", {
                  task_id: res.result.task_id,
                  request_id: res.result.request_id || ''
                })
                .then((task) => {
                  if (task.result.Data.ResultUrl) {
                    state.audioConfig.audio_url = task.result.Data.ResultUrl;
                    state.audioConfig.media_id = task.result.Data?.media_id ||'';
                    state.isSpining = false;
                    state.isPlaying = true;
                    nextTick(() => {
                      audioRef.value && audioRef.value.play();
                    });
                    console.log(audioRef.value);

                    clearInterval(tiem);
                  }
                })
                .catch((err) => {
                  console.log(err);
                })
                .finally(() => {
                  state.isSpining = false; //关闭spin加载
                  state.isPlaying = true; //播放状态为暂停
                  clearInterval(tiem);
                });
            }, 1000);
          });
      }
    };
    return {
      ...toRefs(state),
      showModal,
      handleOk,
      scriptAudioSelection,
      closeAudioSelection,
      playAudioHandle,
      pauseAudioHandle,
      handleAudioEnded,
      audioRef,
      handleCancel,
      scriptAudioSelectionShowModal,
      isAudioConfigChange,
      changeVolume,
    };
  },
});
</script>
<style lang="less" scoped>
.label {
  color: #737a87;
  font-weight: 600;
}

.flex {
  display: flex;
  align-items: center;
}

.border {
  border: 1px solid #ebeef2;
}

.mTop {
  margin-top: 15px;
}

.mRg-10px {
  margin-right: 10px;
}

.pointer {
  cursor: pointer;
}

.secends {
  height: 40px;
  line-height: 40px;
  padding: 0 10px;

  &:hover {
    background: #f4f5f5;
  }
}

.header {
  justify-content: space-between;

  .header-right {
    flex: 1;
    justify-content: flex-end;

    span {
      background: #f4f5f5;
      border-radius: 5px;
      padding: 2px 5px;
      display: flex;
      font-size: 12px;
      align-items: center;
    }

    :deep(.ant-popover-inner-content) {
      .insert-card {
        p {
          color: #009589;
          background: skyblue !important;
        }
      }
    }
  }
}

// 输入框
.editor-box {
  margin: 10px 0;
  height: 100px;
}

// 开始时间
.startTime {
  height: 30px;

  .startTime-left {
    margin-right: 10px;
  }
}

// 音色选择
.tone-select {
  .tone-select-right {
    height: 80px;
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;

    // 头像
    img {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      margin-right: 10px;
      // border: 1px solid #ffffff;
      background: #e6e8ea;
    }

    // 操作按钮
    .operate {
      color: #838a95;
      cursor: pointer; //输入移入显示小手

      .swap-icon,
      .play-icon {
        border: 1px solid #ebeef2;
        padding: 5px 10px;
        font-size: 14px;
      }

      .swap-icon {
        margin-right: 5px;
      }
    }
  }
}

// 配音音量
.dubbing-volume {
  .dubbing-volume-left {
    margin-right: 10px;
  }

  .dubbing-volume-right {
    flex: 1;
    display: flex;
    align-items: center;
    height: 30px;

    .min-volume,
    .max-volume {
      width: 20px;
      height: 100%;
      display: flex;
      align-items: center;
      margin: 0 5px;
    }

    .volume-slider {
      flex: 1;
    }
  }
}

// 应用全部
.all-applicat {
  .all-applicat-left {
    margin-right: 10px;
  }
}

:deep(.ss-form-item) {
  margin-bottom: 0;
}

// 禁用输入框拖拽功能
.no-resize {
  resize: none;
}
</style>
